<?php
/*
 * Plugin Name: PoliPress 
 * Version: 1.0
 * Plugin URI: http://code.google.com/p/poli-press/
 * Description: Search the Hansard and quote members of parliament in Australia from your blog posts. Powered by the <a href="http://openaustralia.org/api">Open Australia API</a>.
 * Author: Sherif Mansour
 * Author URI: http://sherifmansour.com
*/
define('OA_API_URL', 'http://www.openaustralia.org/api/');
define('OA_BASE_URL', 'http://www.openaustralia.org');
define('OA_API_KEY_URL', 'http://www.openaustralia.org/api/key');
define('OA_SEARCH_URL', 'http://www.openaustralia.org/search/?s=');
define('PLUGIN_PATH', $pluginPath = get_settings( 'home' )."/wp-content/plugins/polipress/");
define('DEFAULT_OA_SEARCH_LIMIT', 5);
define('POLIPRESS_URL', 'http://code.google.com/p/poli-press/');


/* If no json_decode exists, use the third-party JSON class */
    //If running old version of php
    if ( !function_exists('json_decode') ){
        function json_decode($content, $assoc=false){
                    require_once 'Services/JSON.php';
                    if ( $assoc ){
                        $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
            } else {
                        $json = new Services_JSON;
                    }
            return $json->decode($content);
        }
    }

    if ( !function_exists('json_encode') ){
        function json_encode($content){
                    require_once 'Services/JSON.php';
                    $json = new Services_JSON;
                   
            return $json->encode($content);
        }
    }


/* PoliPress Plugin Configuration Class */
if ( ! class_exists( 'OA_Admin' ) ) {
	class OA_Admin {

		//This method hooks the PoliPress config page to the menu bar
		function add_config_page() {
			if ( function_exists('add_submenu_page') ) {
				add_submenu_page('plugins.php', 'PoliPress Configuration', 'PoliPress', 1, basename(__FILE__), array('OA_Admin','config_page'));
			}
		} 

		//Below method displays the contents of the PoliPress config page
		function config_page() {
			global $oa_api_key;
			if ( isset($_POST['submit']) ) {
				$oa_api_key = $_POST['oa_api_key'];
				update_option('oa_api_key', $oa_api_key);
			}
	
			?>
			<div class="wrap">
				<h2>PoliPress - Plugin Configuration</h2>
				<p><img src="<?php echo PLUGIN_PATH."/styles/polipress.jpg"; ?>" align="right">PoliPress is a wordpress thet lets you search the Hansard quote members of parliament within your WordPress blog. PoliPress is powered by the <a href="http://openaustralia.org/api" target="_blank">Open Australia API</a>.</p>
				<p>To use PoliPress you must first get an Open Australia API Key. <a href="<?php echo OA_API_KEY_URL; ?>" target="_blank">Click here to get your Open Australia API Key</a>. Once you have your Open Australia API Key, copy and paste it in the text box below:</p>.
				<form action="" method="post" id="openaustralia-conf" style="margin: auto; width: 25em; ">
					<h3><label for="oa_api_key">Open Australia API Key</label></h3>
					<p><input id="oa_api_key" name="oa_api_key" type="text" size="25" value="<?php echo get_option('oa_api_key'); ?>" style="font-family: 'Courier New', Courier, mono; font-size: 1.5em;" /></p>
					<p class="submit"><input type="submit" name="submit" value="Update Open Australia API Key  &raquo;" /></p>
				</form>
				<h2>PoliPress - Using the Plugin</h2>
				<p>Once you have configured PoliPress with your OpenAustralia API Key you are set to go! <a href="<?php echo POLIPRESS_URL; ?>" target="_blank">Click here to read instructions on how to start using PoliPress</a> in your blog.</p>

			</div>
			<?php
			$opt = get_option('oa_api_key');
			if (isset($opt)) {
				if ($opt == "") {
					add_action('admin_footer', array('OA_Admin','warning'));
				} else {
					if (isset($_POST['submit'])) {
						add_action('admin_footer', array('OA_Admin','success'));
					}
				}
			} else {
				add_action('admin_footer', array('OA_Admin','warning'));
			}

		} // end config_page()

		//Below method displays a sucessful message of the PoliPress configuration is set
		function success() {
			echo "
			<div id='openaustralia-warning' class='updated fade-ff0000'><p><strong>Congratulations!<br>The plugin has been configured.</strong></p></div>
			<style type='text/css'>
			#adminmenu { margin-bottom: 7em; }
			#openaustralia-warning { position: absolute; top: 20em; }
			</style>";
		}

		//Below method displays a error message if PoliPress configuration has failed
		function warning() {
			echo "
			<div id='openaustralia-warning' class='updated fade-ff0000'><p><strong>Error:<br>Open Australia API Key is not active.<br>Please check your API Key.</strong></p></div>
			<style type='text/css'>
			#adminmenu { margin-bottom: 6em; }
			#openaustralia-warning { position: absolute; top: 20em; }
			</style>";
		} 

	} // end class GA_Admin

} //endif




/* PoliPress Core - getDebates() */
function getDebates($text){

    //Find the openaustralia tag <openaustralia>
    preg_match_all("/\[polipress[^>]*?\]/", $text, $matches);

    $typeOptions = Array('senate', 'representatives');
    $modeOptions = Array('gid', 'search');
    $mode = "";         //Holds the selected attribute name (gid/search);
    $modeValue = "";    //Holds the selected attribute value of gid or search

    //For each polipress tag
    $m = $matches[0];

    //For each openaustralia tag
    for ($i=0; $i<sizeof($m); $i++)
    {
        $type = strtolower(getAttribute("type", $m[$i]));
        if (!$oa_api_key = get_option('oa_api_key')){
            $text = str_replace($m[$i], "<hr>Error: Open Australia API key not configured. Please login to your Wordpress Admin page and configure a OpenAustralia API Key in your PoliPress Configuration link.<hr>", $text);
        }else if(!in_array($type, $typeOptions)){
            $text = str_replace($m[$i], "<hr>Error: Invalid type.<hr>", $text);
        }else{
            //For that tag, figure out what mode we are in, then grab that modes value.
            for ($x=0; $x<sizeof($modeOptions); $x++){
                if (strtolower(getAttribute($modeOptions[$x], $m[$i]))){
                    $mode = $modeOptions[$x];
                    $modeValue = strtolower(getAttribute($modeOptions[$x], $m[$i]));
                }
            }

            switch ($mode){
                case "gid":     $content = $content = fetch('getDebates', Array ('output'=>'js', 'key'=>$oa_api_key, 'type'=>$type, 'gid'=>$modeValue));;
                                if ($content)
                                {
                                    $speech = "";
                                    foreach ($content as $c)
                                    {
                                        //If we have a speaker
                                        if ($c->speaker)
                                        {
                                            //Construct blockquote of speakers speech
                                            $speakerName = $c->speaker->first_name." ".$c->speaker->last_name;
                                            $speech .="<blockquote class=\"style1\"><span class=\"style1\">";
                                                if ($c->speaker->image){
                                                    $speech .= "<img src=\"".OA_BASE_URL.$c->speaker->image."\" border=\"0\" alt=\"$speakerName\" align=\"left\">";
                                                }
                                                $speech .= $c->body;
                                                $speech .= "<cite>- <a href=\"".OA_BASE_URL.$c->speaker->url."\" target=\"_blank\">".$speakerName."</a> (".$c->speaker->party.")</cite>";
                                                if ($c->totalcomments > 0){
                                                    $speech .= "<img class=\"smallicon\" src=\"".PLUGIN_PATH."styles/comment_icon.gif\"> <a href=\"".OA_BASE_URL.$c->commentsurl."#comments\" target=\"_blank\">{$c->totalcomments} comments</a> | ";
                                                }
                                                $speech .= "<a href=\"".OA_BASE_URL.$c->listurl."\" target=\"_blank\">Read context</a>";
                                                $speech .="</span></blockquote>";
                                        }
                                    }

                                    if ($speech != ""){
                                        $text = str_replace($m[$i], $speech, $text);
                                    }else{
										if ($content->error){
											$text = str_replace($m[$i], "<hr>Error making getDebates call. Error is: <b>".$content->error."</b><hr>", $text);
										}else{
	                                        $text = str_replace($m[$i], "<hr>No OpenAustralia Speech Found<hr>", $text);
										}
                                    }
                                }
                                else{
                                    $text = str_replace($m[$i], "<hr>Unable to make OpenAustralia API Call. Check your API Key is correct and the OpenAustralia site is up.<hr>", $text);
                                }
                                break;

                case "search":  $numResults = getAttribute("num", strtolower($m[$i]));
								$numResults = ((is_numeric($numResults)) ? $numResults : DEFAULT_OA_SEARCH_LIMIT);	//If numResults is set, use that, otherwise default to config
								$totalResultsDisplayed = 0;
								//TODO: add additonal , 'num'=>$numResults paramater below when this is fixed http://tickets.openaustralia.org/browse/OA-288
								$content = fetch('getDebates', Array ('output'=>'js', 'key'=>$oa_api_key, 'type'=>$type, 'search'=>$modeValue));
                                if ($content)
                                {
                                    $searchResults = "<div class=\"navlist\" id=\"navlist\"><ul id=\"navlist\" class=\"navlist\">";
                                    foreach ($content as $c){
                                       for ($x=0; $x<sizeof($c); $x++)
                                       {
										   //TODO: This can be removed once result limit feature is implemented in OA API.
										   if ($x < $numResults){
											   if ($c[$x]->body){
													$date = split('-', $c[$x]->hdate);
													$printDate = date("d/m/Y", mktime(0, 0, 0, $date[1], $date[2], $date[0]));
													$speakerName = $c[$x]->speaker->first_name." ".$c[$x]->speaker->last_name;
													$searchResults .= "<li class=\"navlist\"><img src=\"".OA_BASE_URL."/images/mps/".$c[$x]->speaker->person_id.".jpg\" align=\"left\">".$c[$x]->body."<br><cite>- <a href=\"".OA_BASE_URL.$c[$x]->speaker->url."\" target=\"_blank\">".$speakerName."</a> (".$printDate.")</cite> <a href=\"".OA_BASE_URL.$c[$x]->listurl."\" target=\"_blank\">Read context</a></li>";
													$totalResultsDisplayed++;
											   }
										   }
                                       }
                                    }
                                    $searchResults .= "</ul></div>";

									$remainingResults = ($content->info->total_results - $totalResultsDisplayed);
									if ($content->info->total_results <= 0 ){
										$text = str_replace($m[$i], "<hr>No OpenAustralia Speech Found<hr>", $text);
									}else if ($remainingResults >= 1){
										$searchResults .= "There are ".($remainingResults)." more speeches containing '".$modeValue."'. <a href=\"".OA_SEARCH_URL.urlencode($content->info->s)."\" target=\"_blank\">Click here to view them all.</a><br>";
									}
									$text = str_replace($m[$i], $searchResults, $text);
                                }else{
                                     $text = str_replace($m[$i], "<hr>Unable to make OpenAustralia API Call. Check your API Key is correct and the OpenAustralia site is up. Error is: ".$content->error."<hr>", $text);
                                }
                                break;

            }

        }//else no errors
    }

    return $text;
}


//Wrapper to make the OA API Call
function fetch($uri, $url_args=null){

    //Build the API URL
    if (!$url_args) $url_args = array();
    $url_args["output"] = "js";
    $pairs = array();
    foreach ($url_args as $name => $value) {
        $pairs[] = $name . "=" . urlencode($value);
    }
    $url = OA_API_URL. $uri . "?" . join("&", $pairs);

    //Make the API Call
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
    curl_setopt($c, CURLOPT_URL, $url);
    $content = curl_exec($c);
    $info = curl_getinfo($c);
    curl_close($c);

    //Return the result
    if ($info["http_code"] != 200) {
        return null;
    }else{
        return(json_decode($content));
    }
}


//Gets the attribute value from the Custom tag
   function getAttribute($attrib, $tag){
      //get attribute from html tag
      $re = '/' . preg_quote($attrib) . '=([\'"])?((?(1).+?|[^\s>]+))(?(1)\1)/is';
      if (preg_match($re, $tag, $match)) {
         return urldecode($match[2]);
      }
      return false;
   }

//add open australia css
function addStyles(){
    echo "\n\t<link type=\"text/css\" rel=\"stylesheet\" href=\"".PLUGIN_PATH."styles/polipress.css\" media=\"screen\" />\n";
}


//$oa_api_key = get_option('oa_api_key');

// adds the menu item to the admin interface
add_action('admin_menu', array('OA_Admin','add_config_page'));

//Adding the CSS Header
add_action( 'wp_head', 'addStyles');

//first param = hook, second param is the action 
add_filter('the_content', 'getDebates');